package main.java.middle;

/**
 * @Author: 郑国荣
 * @Date: 2023-09-09-16:20
 * @Description:
 */
public class ThreeSumClosest {
    public int threesumClosest(int[] nums,int target){
        //三指针算法
        int length = nums.length;
        if(length <3) return 0;
        int left =0,medium =1,right =2;
        int def= Math.abs(target-(nums[left]+nums[medium]+nums[right]));
        while(left!=length-3){
            if(right<length-1) right++;
            else if(medium!=right-1) {
                medium++;
                right = medium+1;
            } else if(left!=length-3){
                left++;
                medium=left+1;
                right = left+2;
            }
            def = Math.min(def,Math.abs(target-(nums[left]+nums[medium]+nums[right])));
        }
        return target-def;
    }

    public static void main(String[] args) {
        int[] nums = {1,1,1,0};
        ThreeSumClosest threeSumClosest = new ThreeSumClosest();
        int i = threeSumClosest.threesumClosest(nums, 3);
        System.out.println(i);
    }
}
